﻿   using NB.MGJ.Common.API;
using NB.MGJ.Common.Helper;
using NB.MGJ.Common.Utility;
using NB.MGJ.Model;
using NB.MGJ.Model.AntiFleeingEntity;
using NB.MGJ.Service;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace NB.MGJ.API
{
    public class fillTheBoxModel
    {
        public string caseCode { get; set; }
        public string[] SingleCode { get; set; }
        public int userid { get; set; }
        public int type { get; set; }
    }
    public partial class ApiMGJFleedToolsController : ApiBaseController<LogOnUserModel>
    {

        FleeGoodsService fs = new FleeGoodsService();
        ManagerService ms = new ManagerService();
        #region 分离单标
        [Route("nbapi/fleedtool/singlestandard")]
        [HttpGet]
        public IHttpActionResult SeparationSingle(string code,int userid)
        {
            try
            {
                Sys_User user = ms.GetUserInfoById(userid);
                code = code.Trim();             
                AntiFleeing_DevanningRecords record = new AntiFleeing_DevanningRecords();
                record.CZCode = code;
                var list = new List<V_ListBox>();
                string result = Check_Out(code, user, out list);
                if (!string.IsNullOrEmpty(result)) return ApiFail(result);
                if (list[0].Wl_Code != code)
                {
                    int i = fs.AddRecords(list[0].Wl_Code, code);
                    if (i < 0) return ApiFail("分离失败！");
                }
                record.GLCode = list[list.Count-1].ParentCode;
                int id = fs.UpdateParentCode(code, "0");
                if (id > 0)
                {
                    //添加操作记录
                    record.Type = 2;//分离单标
                    record.CreateBy = user.ID;
                    record.CreateOn = DateTime.Now;
                    fs.RecordAdd(record);
                    return ApiSuccess("分离成功！");
                }
                else
                {
                    return ApiFail("分离失败！");
                }
               
            }
            catch (Exception e)
            {
                return ApiFail(e.Message);
            }
        }
        #endregion

        #region 装箱

        [Route("nbapi/fleedtool/fillThebox")]
        [HttpPost]
        public IHttpActionResult fillThebox([FromBody]fillTheBoxModel obj)
        {
            try
            {
                string BoxCode = obj.caseCode;
                string[] arr = obj.SingleCode;
                int userid =obj.userid;
                int type=obj.type;
                Sys_User user = ms.GetUserInfoById(userid);
                string tableName = "nbcodemain.AntiFake_Digitcode" + BoxCode.Substring(0,AppConst.SubStrLen);
                AntiFleeing_PackBox model = fs.GetGenCodeInfo(BoxCode.TrimStart());
                model.FilePath = fs.WriteTxt(arr, "ZX" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt");
                model.Type = type;//手机端装箱
                model.EnterpriseID = user.EnterpriseId;
               // model.FormCode = fs.PackBoxGetCode(user.EnterpriseId.ToString());
                model.FormCode = DateTime.Now.ToString("yyyyMMddHHmmss");
                model.CreateLoginID = user.ID;
                model.CreateLoginName = user.LoginName;
                model.CreateDate = DateTime.Now;
                model.ViewDel = 0;
                model.ScalingRelation = "1-" + arr.Length;
                model.Num = arr.Length + 1;
                model.Status = 2;
               // model.Explain = BoxCode + "," + SingleCodes;
                model.ChangeLoginID = user.ID;
                model.ChangeLoginName = user.LoginName;
                model.ChangeDate = DateTime.Now;
                model.Bacth = BoxCode.TrimStart().Substring(4, AppConst.SubBatchLen);
                int id = 0;
                model = WipeNullHelper.WipeNull<AntiFleeing_PackBox>(model);//去空
                id = fs.PackBoxAdd(model);
                if (id > 0)
                {  //改变生码表信息
                    string SingleCodes = string.Empty;
                    SingleCodes = string.Join(",", arr);//数组转成字符串
                    fs.UpdateBoxCode(BoxCode, SingleCodes, tableName);
                    //添加装箱记录
                    AntiFleeing_DevanningRecords record = new AntiFleeing_DevanningRecords();
                    record.CZCode = BoxCode;
                    record.GLCode = arr.ToString();
                    record.Type = type;//手机端装箱
                    record.CreateBy = user.ID;
                    record.CreateByName = user.RealName;
                    record.CreateOn = DateTime.Now;
                    fs.RecordAdd(record);
                    for (int i = 0; i < arr.Length; i++)
                    {
                        record = new AntiFleeing_DevanningRecords();
                        record.CZCode = arr[i];
                        record.GLCode = BoxCode;
                        record.Type = type;//手机端装箱
                        record.CreateBy = user.ID;
                        record.CreateByName = user.RealName;
                        record.CreateOn = DateTime.Now;
                        fs.RecordAdd(record);
                    }
                    return ApiSuccess(new { id = 1, text = "添加成功!" });

                }
                else
                {
                    return ApiFail( "添加失败!" );

                }
                // return ApiSuccess(true);
            }
            catch (Exception e)
            {
                return ApiFail(e.Message);
            }
        }
        #endregion

        #region 列出整箱
        [Route("nbapi/fleedtool/listbox")]
        [HttpGet]
        public IHttpActionResult ListBox(string key,int userid)
        { // 0 表是没找到数据或表          1 代表有数据但不是本机构生的码          2 代表成功
            try
            {
                key = key.Trim();
                Sys_User user = ms.GetUserInfoById(userid);
                Organization_Enterprise ent = fs.GetMaxEnterpriseIInfo(user.EnterpriseId.Value);//获取最上级的机构信息
                //码的表是否存在
                int TabIsExist = fs.CheckTable(key, ent.ID);
                if (TabIsExist == 2)
                {
                  //  List<V_ListBox> list = fs.ListGetTable(key);
                    var list = fs.GetDigitCodeList(key);
                    return ApiSuccess(list);
                }
                else if (TabIsExist == 1)
                {
                    return ApiFail("该码不属于当前机构");
                }
                else
                    return ApiFail("该码不存在！");
            }
            catch (Exception e)
            {
                return ApiFail(e.Message);
            }

        }
        #endregion

        #region 窜货验证
         [ApiVisitFilter("antiFleeing")]
        [Route("nbapi/fleedtool/fleegoodsresult")]
        [HttpGet]
        public IHttpActionResult FleeGoodsResult(string key,int userid)
        {
            try
            {
                key = key.Trim();
                Sys_User user = ms.GetUserInfoById(userid);
                //判断当前码是否属于当前机构
                if (user.EnterpriseId != 1)
                {
                    Organization_Enterprise ent = fs.GetMaxEnterpriseIInfo(user.EnterpriseId.Value);
                    if (key.Trim().Substring(0, 4) != ent.Code) return Json(" ");
                }
                // 查出库表
                AntiFleeing_OutboundDetails model = fs.GetTableByCode(key);
                if (model == null)
                {
                    //获取上级码
                    // string tableName = "nbcodemain.AntiFake_Digitcode" + key.Substring(0, 6);
                    var list = fs.ListGetTable(key);
                    var parentCode = list[0].Wl_Code;
                    //上级是否出库信息
                    model = fs.GetParentTableByCode(parentCode);
                    if (model == null) return ApiFail("");
                    else return ApiSuccess(Model(model.FormCode, key, model.DistributorID));
                }
                else
                {
                    return ApiSuccess(Model(model.FormCode, key, model.DistributorID));
                }
            }
            catch (Exception)
            {
                return ApiFail("");
            }
          
        }
         public FleeingProving Model(string formCode, string code, int disId)
        {
            FleeingProving FPModel = new FleeingProving();
            AntiFleeing_IOWarehouse model = fs.GetModelByFormCode(formCode);
            AntiFleeing_Distributor discModel = fs.GetTableById(disId);
            FPModel.CompanyName = model.EnterpriseName;
            FPModel.ProductName = model.ProductName;
            if (discModel != null)
            {
                DateTime date = (DateTime)model.CreateDate;
                FPModel.ChuKuDate = date.ToString("yyyy-MM-dd HH:mm:ss");
                FPModel.FWDistributor = discModel.Name;
                FPModel.Contact = discModel.Contacts;
                FPModel.Address = discModel.ProvinceName + "-" + discModel.CityName + "-" + discModel.RegionName;
                FPModel.Precinct = discModel.JurisdictionPrivanceName + "-" + discModel.JurisdictionCityName + "-" + discModel.JurisdictionRegionName;
                if (discModel.IsCrossArea.ToString() == "1")
                    FPModel.CrossArea = discModel.AcrossPrivanceName + "-" + discModel.AcrossCityName + "-" + discModel.AcrossRegionName;
                else FPModel.CrossArea = "无";
                FPModel.SaleArea = discModel.SalesArea;
                FPModel.FWSaleArea = model.SaleAreaName;
            }
            return FPModel;
        }
        #endregion

        #region 调货
        [Route("nbapi/fleedtool/adjustcargo")]
        [HttpPost]
        public IHttpActionResult AdjustCargo([FromBody]AntiFleeing_Transshipment model)
        {
            try
            {     
                Sys_User user = ms.GetUserInfoById(model.CreateLoginID.Value);
                if (model.Codes == null)
                {
                    model.Codes = model.Code_String.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
                }
                string[] arr = model.Codes;
                AntiFleeing_Transshipment model0 = fs.GetModel<AntiFleeing_Transshipment>(arr[0]);
                if (model0 == null) return ApiFail("物流码不存在！");
                else model.ProductID = model0.ProductID;
                model.FilePath = fs.WriteTxt(arr, "DH" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt");
                model.Type = 3;
                model.EnterpriseID = user.EnterpriseId;
                model.CreateDate = DateTime.Now;
                model.ViewDel = 0;
               
                model.Num = arr.Length;
                int count = fs.SearchChildrenCount(model.Codes[0]);
                model.DragNum = count * model.Num;
                model.Status = 1;//待导入
               // model.FilePath = path;
                model.CheckStatus = 1;//待审核
                model.FromDistributor = user.Distributor;
                int m = fs.TranAdd(model);
                if (m <= 0) return ApiFail("提交失败！");
                //批量冻结
                fs.FrozenOrThaw(string.Join(",",arr), 1);
                //添加处理状态
                AntiFleeing_ProcessingType typeModel = new AntiFleeing_ProcessingType();

                typeModel.FormCode = model.FormCode;
                typeModel.Type = 1;//调货货
                typeModel.ViewDel = 0;
                typeModel.CreateLoginID = user.ID;
                typeModel.CreateLoginName = user.LoginName;
                typeModel.CreateDate = DateTime.Now;
                typeModel.Status = 0;//未审核
                List<AntiFleeing_Distributor> list = fs.GetEnterAllParent(user.Distributor.Value);
                if (list.Count <= 0) typeModel.EnterpriseID = LogOnUser.EnterpriseId;
                else
                {
                    string enterId = list[0].EnterpriseId.ToString();//直接返回给厂家
                    typeModel.EnterpriseID = int.Parse(enterId);//当前用户的上级机构
                }


                int n = fs.ProcTypeAdd(typeModel);
                if (n <= 0) return ApiFail("申请失败！");
                return ApiSuccess(m);


            }
            catch (Exception e)
            {
                return ApiFail(e.Message);
            }
        }
        #endregion
    
    }
}
